Published on

go广播聊天室

Authors

sender

cmd/client/main.go

package main

import (
	"bufio"
	"fmt"
	"gotest/boardcast"
	"os"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("leak of name..")
	}

	msg := make(chan []byte)
	go boardcast.Client(msg)
	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		bytes := make([]byte, 0, len(scanner.Bytes()))
		name := []byte(os.Args[1] + ":")
		for _, b := range name {
			bytes = append(bytes, ^b)
		}

		for _, b := range scanner.Bytes() {
			bytes = append(bytes, ^b)
		}
		msg <- bytes
	}
}

receiver

package main

import "gotest/boardcast"

func main() {
	boardcast.Server()
}

udp boardcast

package boardcast

import (
	"log"
	"net"
)

func Client(m chan []byte) {
	conn, err := net.Dial("udp", net.IPv4bcast.String()+":3000")
	defer conn.Close()
	if err != nil {
		log.Fatalln(err)
		return
	}

	for {
		select {
		case msg := <-m:
			_, err := conn.Write(msg)
			if err != nil {
				log.Println(err)
				return
			}
		}
	}

}

func Server() {
	addr, err := net.ResolveUDPAddr("udp", ":3000")
	if err != nil {
		log.Fatalln(err)
		return
	}

	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		log.Fatalln(err)
		return
	}

	data := make([]byte, 1024)
	msg := make([]byte, 1024)

	for {
		msg = msg[:0]
		n, _, err := conn.ReadFrom(data)
		if err != nil {
			return
		}

		for i, v := range data {
			msg = append(msg, ^v)
			if n-1 == i {
				msg = msg[:n]
				break
			}
		}
		log.Println("msg:", string(msg))
	}
}